package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiPurchaseEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PurchaseDao;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.product.PurchaseProductEnum;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.PurchaseSubDataModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author Jian.Wang
 * @date  2019-01-25 14:05
 **/
@Service("PurchaseModel")
public class PurchaseModelImpl implements PurchaseModel{

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PurchaseDao purchaseDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PurchaseSubDataModel purchaseSubDataModel;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private InstockModel instockModel;

    /**
     * 采购合同数据插入
     * @param entity 供应商实体
     * @author Jian.Wang
     * @date 2019/1/23 20:27
     * @since v1.0
     * @throws XbbException 异常
     * @return Integer
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(PurchaseEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = purchaseDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        return insert;
    }
    /**
     * 采购合同数据更新
     * @param entity 供应商实体
     * @author Jian.Wang
     * @date 2019/1/23 20:27
     * @since v1.0
     * @throws XbbException 异常
     * @return Integer
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(PurchaseEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer integer = purchaseDao.update(entity);

        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        if (Objects.equals(1, integer) || Objects.equals(1, updateSub)) {
            // 更新时间
            integer = purchaseDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return integer;
    }
    /**
     * 采购合同数据查询多个
     * @param param 参数
     * @author Jian.Wang
     * @date 2019/1/23 20:27
     * @since v1.0
     * @return List
     */
    @Override
    public List<PurchaseEntityExt> findEntitys(Map<String, Object> param) {
        List<PurchaseEntityExt> entitys = purchaseDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        }
        return entitys;
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return purchaseDao.getEntitysCount(param);
    }

    /**
     * 查询单个实体
     *
     */
    @Override
    public PurchaseEntityExt getByKey(Long key, String corpid) {
        PurchaseEntityExt purchaseEntityExt = purchaseDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(purchaseEntityExt), IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        return purchaseEntityExt;
    }


    /**
     * 保存
     *
     * @param purchase 采购合同保存
     * @author Jian.Wang
     * @date 2019/2/21 17:19
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer save(PurchaseEntityExt purchase) throws XbbException {
        if (purchase.getId() == null || purchase.getId().equals(0L)) {
            return insert(purchase);
        }
        return update(purchase);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = purchaseDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PURCHASE);
        }
        if (!subList.isEmpty()) {
            purchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid,boolean needThrow) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = purchaseDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PURCHASE,needThrow);
        }
        if (!subList.isEmpty()) {
            purchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = purchaseDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PURCHASE, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            purchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        Integer integer = purchaseDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PURCHASE);

        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PURCHASE, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        return purchaseDao.deleteByKey(key,corpid);
    }

    @Override
    public List<AiPurchaseEntity> getPurchaseList4Ai(String corpid, List<Long> idIn) {
        return purchaseDao.getPurchaseList4Ai(corpid, idIn);
    }

    @Override
    public List<String> getPurchaseJsonExtractListByIn(String corpid, List<String> purchaseIds, String attr){
        attr = "$." + attr;
        return purchaseDao.getPurchaseJsonExtractListByIn(corpid, purchaseIds, attr);
    }

    @Override
    public List<PurchaseEntityExt> getPurchaseListByIdIn(String corpid,List<Long> idIn){
        List<PurchaseEntityExt> entityExts = purchaseDao.getPurchaseListByIdIn(corpid, idIn);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);
        return entityExts;
    }

    @Override
    public List<String> getCorpidList() {
        return purchaseDao.getCorpidList();
    }

    @Override
    public List<PurchaseEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return purchaseDao.findEntitys(param);
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     * @author Jian.Wang
     * @date 2019-02-25 21:23
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        formatAddExplain(formatExplainDTO);
    }

    /**
     * 新建时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     * @author long.rao
     * @date 2019-02-13 20:53
     */
    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        String platForm = formatExplainDTO.getPlatform();
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                boolean unitNoEdit = false;
                if (Objects.nonNull(dataEntity) && !Objects.equals(formatExplainDTO.getFromCopy(), true)) {
                    if (CollectionsUtil.isEmpty(dataEntity.getData().getJSONArray(PurchaseEnum.INSTOCK_ID.getAttr()))) {
                        //校验审批中是否有下游入库单
                        if (commonHelp.isOpenWorkFlow(corpid)) {
                            List<PaasFormDataEntityExt> approvalPaasFormDataList = instockModel.findInstockList(corpid, InstockTypeEnum.PURCHASE_INSTOCK.getCode(), dataEntity.getId(),
                                    Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                            if (!approvalPaasFormDataList.isEmpty()) {
                                unitNoEdit = true;
                            }
                        } else {
                            List<PaasProcessRelatedDataEntity> entities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(dataEntity.getId(), XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), corpid);
                            if (!entities.isEmpty()) {
                                unitNoEdit = true;
                            }
                        }
                    }else{
                        unitNoEdit = true;
                    }
                }
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.PURCHASE, corpid, BasicConstant.ONE, unitNoEdit);
                /*if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(PurchaseEnum.SUPPLIER_ID.getAttr());
                }*/
            } else if( Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr())){
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_VIEW.getAlias()) ) {
                    fieldAttrEntity.setVisible(0);
                }
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_ADD.getAlias()) ) {
                    fieldAttrEntity.setEditable(0);
                }
            }else if(Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.PRODUCT_TOTAL.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if ((Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.ADD_PAY_SHEET.getAttr()))){
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_VIEW.getAlias()) ) {
                    fieldAttrEntity.setVisible(0);
                }
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_ADD.getAlias()) ) {
                    fieldAttrEntity.setEditable(0);
                }
            }
        }
    }

    /**
     * 采购合同编辑格式化数据格式
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result              要返回的jsonobject
     * @throws XbbException 参数格式错误异常
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        if (StringUtil.isEmpty(result.getString(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr()))) {
            Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(result, PurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
            SupplierEntityExt supplierEntityExt = supplierModel.getByKey(supplierId, saasAnalysisDataDTO.getCorpid());
            if (Objects.nonNull(supplierEntityExt)) {
                String name = FastJsonHelper.getStringOrDefaultFromFormData(supplierEntityExt.getData(), SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                result.put(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), name);
            }
        }
        showFormatHelp.formatLinkBusiness4ShowBySource(result, PurchaseEnum.SUPPLIER_ID.getAttr(), PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), PurchaseEnum.SUPPLIER_ID.getFieldType(), XbbRefTypeEnum.SUPPLIER.getCode(), XbbRefTypeEnum.PURCHASE.getCode(), saasAnalysisDataDTO.getCorpid());
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseEnum.SUPPLIER_ID.getAttr(), PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), PurchaseEnum.SUPPLIER_ID.getFieldType());
    }

    @Override
    public void getProductList(Boolean forLinkAdd, String corpid, List<PurchaseProductEntity> purchaseProductEntityList, JSONObject dataObject, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataObject, StringConstant.PRODUCT_LIST, new JSONArray());
        JSONObject others = FastJsonHelper.getJsonObjectOrDefaultFromFormData(dataObject, BusinessConstant.OTHERS, new JSONObject());
        Double discount = 0D;
        Double otherCharge = 0D;
        if (others != null && !others.isEmpty()) {
            discount = getDoubleOrDefaultFromFormData(others, StringConstant.PURCHASE_DISCOUNT, 0D);
            otherCharge = getDoubleOrDefaultFromFormData(others, StringConstant.PURCHASE_OTHER_CHARGE, 0D);
        }
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            // 采购单价
            Double productPrice = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCT_PRICE.getSaasAttr(), 0D);
            // 采购金额
            Double money = productNum * productPrice;
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                JSONArray supplierArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(productObject, ProductEnum.SUPPLIER.getAttr(), new JSONArray());
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                if (Objects.nonNull(forLinkAdd) && forLinkAdd) {
                    productPrice = getDoubleOrDefaultFromFormData(productObject, ProductEnum.COST.getAttr(), 0D);
                    money = productNum * productPrice;
                }
                PurchaseProductEntity productEntity = new PurchaseProductEntity();
                productEntity.setProductUnit(unit);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setBarcode(barcode);
                productEntity.setProductPrice(productPrice);
                productEntity.setProductNo(productNo);
                productEntity.setMoney(money);
                productEntity.setMemo(memo);
                productEntity.setSort(sort);
                productEntity.setProductSpecification(specification);
                productEntity.setDiscount(discount);
                productEntity.setOtherCharge(otherCharge);
                productEntity.setLinkSupplierId(supplierArr);
                productEntity.setSort(sort);
                purchaseProductEntityList.add(productEntity);
            }
        }
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        //采购合同仅能退货一次
        // 获取关联产品
        List<PurchaseProductEntity> purchaseProductEntityList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(PurchaseEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, PurchaseEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(false, corpid, purchaseProductEntityList, data.getJSONObject(PurchaseEnum.PRODUCT.getAttr()), productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(PurchaseEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        PurchaseProductEntity purchaseProductEntity = new PurchaseProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            purchaseProductEntity.setId(subProductId);
                        }
                        purchaseProductEntity.setData(jsonObject);
                        purchaseProductEntityList.add(purchaseProductEntity);
                    }
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            purchaseProductEntityList = purchaseProductModel.getProductsByPurchaseId(corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        JSONArray productArray = new JSONArray();
        for (PurchaseProductEntity purchaseProductEntity : purchaseProductEntityList){
            JSONObject json = formatSingleProduct(purchaseProductEntity);
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,purchaseProductEntity.getId());
                if (Objects.isNull(purchaseProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(purchaseProductEntity.getCorpid(),purchaseProductEntity.getProductUnit()));
            }
            json.put("refId",purchaseProductEntity.getId());
            productArray.add(json);
        }
        data.put(PurchaseEnum.PRODUCT.getAttr(),productArray);
    }

    @Override
    public JSONObject formatSingleProduct(PurchaseProductEntity purchaseProductEntity) {
        JSONObject json = purchaseProductEntity.getData();
        Double rate = showFormatHelp.approvalSetBusinessUnit(json, purchaseProductEntity);
        if (Objects.isNull(json) || json.isEmpty()) {
            json = new JSONObject();
            for (PurchaseProductEnum purchaseProductEnum : PurchaseProductEnum.values()) {
                String attr = purchaseProductEnum.getAttr();
                switch (purchaseProductEnum) {
                    case PRODUCT:
                        json.put(attr, purchaseProductEntity.getProductId());
                        break;
                    case NUM:
                        json.put(attr, purchaseProductEntity.getProductNum());
                        break;
                    case PURCHASE_PRICE:
                        json.put(attr, purchaseProductEntity.getProductPrice());
                        break;
                    case SUBTOTAL:
                        json.put(attr,purchaseProductEntity.getProductPrice() * purchaseProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr, purchaseProductEntity.getMemo());
                        break;
                    case UNIT:
                        json.put(attr,purchaseProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        }
        if (Objects.nonNull(purchaseProductEntity.getInstockNum())) {
            json.put(PurchaseProductEnum.INSTOCK_NUM.getAttr(), Arith.div(purchaseProductEntity.getInstockNum(), rate));
            double num = Arith.sub(purchaseProductEntity.getProductNum(), purchaseProductEntity.getInstockNum());
            double waitInstockNum = num >= 0 ? num : 0D;
            json.put(PurchaseProductEnum.WAIT_INSTOCK_NUM.getAttr(), Arith.div(waitInstockNum, rate));
        }
        if (Objects.nonNull(purchaseProductEntity.getOutstockNum())) {
            json.put(PurchaseProductEnum.RETURN_NUM.getAttr(), Arith.div(purchaseProductEntity.getOutstockNum(), rate));
        }
        return json;
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = purchaseDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE);
        paasEsModel.update(insertDTO);
        return success;
    }
}
